﻿using Lapis.Share;
using Lapis.Shell.Events;
using Lapis.Shell.Views;
using System.Windows.Controls;
using TabControl = HandyControl.Controls.TabControl;
using TabItem = HandyControl.Controls.TabItem;

namespace Lapis.Shell.ViewModels
{
    /// <summary>
    /// Tab页面内容视图模型
    /// </summary>
    public class TabPagesContentViewModel : BaseViewModel
    {
        private TabControl _tabControl;

        protected override void OnLoad()
        {
            _tabControl = TryFindView<TabPagesContent>(ShellRegionNames.TabPagesContentRegion)?.FindName("tabControl") as TabControl;

            EventAggregator.GetEvent<PageSelectedEvent>().Subscribe(OnPageSelected);
        }

        /// <summary>
        /// 页面选中事件处理
        /// </summary>
        /// <param name="page"></param>
        private void OnPageSelected(PageInfo page)
        {
            try
            {
                var existItem = FindItem(_tabControl, page.RegionName);
                if (existItem != null)
                {
                    existItem.IsSelected = true;
                }
                else
                {
                    // 创建页面区域控件
                    var pageContentControl = new ContentControl();
                    pageContentControl.SetRegionName(page.RegionName);

                    var item = new TabItem
                    {
                        Name = page.RegionName,     // 区域名称,如:RegionOne、RegionTwo
                        Header = page.DisplayName,  // 页面名称
                        IsSelected = true,
                        Content = pageContentControl
                    };

                    _tabControl.Items.Add(item);
                }
            }
            catch { }
        }

        private TabItem FindItem(TabControl tc, string name)
        {
            foreach (TabItem item in tc.Items)
            {
                if (item.Name == name)
                {
                    return item;
                }
            }
            return null;
        }
    }
}